package servlet;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.JDBCUtil;
import service.EmployeeService;
import service.impl.EmployeeServiceImpl;
//继承自HttpServlet
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet{
	//创建service层对象employeeServiceImpl
	private  EmployeeService employeeServiceImpl=new EmployeeServiceImpl();
	
	//处理post类型的请求，request请求，response 响应
	public void doPost(HttpServletRequest request,HttpServletResponse response) {
		//获取请求里的参数,parameter的参数来自于html页面里组件的name属性
		String username=request.getParameter("username");
		String password=request.getParameter("password");
		//业务功能：参数值赋值给sql的预编译对象里的？
		
	    //调用service层的EmployeeServiceImpl
		int loginFlag=employeeServiceImpl.login(username, password);
		//如果结果集中有数据的话，表示登录成功，否则登录失败
		try {
			if(loginFlag==1) {
				//设置cookie,获取cookie时长
				String timeLength=request.getParameter("timeLength");
				int days=0;
				if(timeLength!=null)
					days=Integer.parseInt(timeLength);
				if(days!=0) {
					//创建cookie变量
					Cookie usernameCookie=new Cookie("meeting.username", username);
					Cookie passwordCookie=new Cookie("meeting.password", password);
					//设置cookie时长
					usernameCookie.setMaxAge(days*24*3600);
					passwordCookie.setMaxAge(days*24*3600);
					//从服务器端往客户端写cookie
					response.addCookie(usernameCookie);
					response.addCookie(passwordCookie);
					
				}
				
				
				//将username作为会话变量
				//request.setAttribute("username", username);
				request.getSession().setAttribute("username", username);
				//登录成功，转到 欢迎页面
				response.sendRedirect("index.jsp");
				}
			else {
				//登录失败，停留在登录页面
				response.sendRedirect("login.jsp");
			}
		}  catch (IOException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		
		
		
	}
	public void doGet(HttpServletRequest request,HttpServletResponse response) {
		//获取请求里的参数,parameter的参数来自于html页面里组件的name属性
		String username=request.getParameter("username");
		String password=request.getParameter("password");
		String age=request.getParameter("age");
		System.out.println(username);
		System.out.println(password);
		System.out.println(age);
	}
	@Override
	protected void doHead(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO 自动生成的方法存根
		super.doHead(req, resp);
	}

}
